<template>
  <div class="app-container">
    <div class="head">
      <el-form label-position="right" label-width="auto" :model="formLabelAlign" inline>
        <el-form-item label="开始时间">
          <div class="block">
            <el-date-picker
                v-model="formData.labelDate"
                type="datetime"
                placeholder="Pick a Date"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
          <!--          <el-date-picker style="width: 150px;" v-model="formData.labelDate" type="date" placeholder="选择日期"-->
          <!--                          value-format="YYYY-MM-DD" :default-value="new Date()"/>-->
        </el-form-item>
        <el-form-item label="结束时间">
          <div class="block">
            <el-date-picker
                v-model="formData.labelDateEnd"
                type="datetime"
                placeholder="Pick a Date"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
          <!--          <el-date-picker style="width: 150px;" v-model="formData.labelDate" type="date" placeholder="选择日期"-->
          <!--                          value-format="YYYY-MM-DD" :default-value="new Date()"/>-->
        </el-form-item>
        <el-form-item label="生产车间">
          <el-select v-model="formData.workshop" placeholder="Select" style="width: 150px" clearable
                     @change="handleWorkshopChange">
            <el-option v-for="item in workshopList" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="机台" label-width="40px">
          <el-select v-model="formData.machine" placeholder="Select" style="width: 150px" clearable>
            <el-option v-for="item in showMachineList" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="定量" label-width="40px">
          <el-input v-model="formData.ration" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="标签状态">
          <el-select v-model="formData.labelStatus" placeholder="Select" style="width: 150px" clearable>
            <el-option v-for="item in labeltatusArr" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="打印人员">
          <el-input v-model="formData.username" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="统计日期">
          <el-date-picker style="width: 150px;" v-model="formData.collectDate" type="date" placeholder="选择日期"
                          value-format="YYYY-MM-DD" :default-value="new Date()"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleList" type="primary">查询</el-button>
          <el-button @click="handleSubmit" type="primary">提交</el-button>
          <el-button @click="handleExport" type="warning">导出</el-button>
        </el-form-item>
        <el-form-item>

          <div style="width: 400px;">
            总重量： {{ collect.weight }} <span style="padding-left: 45px;">总件数： {{ collect.num }}  </span>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="center">
      <el-table ref="tableRef" :data="tableData" style="width: 100%" border height="100%"
                @selection-change="handleSelectionChange" @row-click="handleRowClick" v-loading="loading">
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="55" label="序号" align="center"/>
        <el-table-column v-for="item in columns" :key="item.prop" :property="item.prop" :label="item.label"
                         :width="item.width"></el-table-column>
      </el-table>

      <div class="bottom">
        <el-pagination style="float: right; margin-top: 10px;" v-model:current-page="currentPage"
                       v-model:page-size="pageSize" :page-sizes="[50, 100, 150, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" background/>
      </div>
    </div>
  </div>

</template>
<script setup lang="ts">
import {ref, onMounted, onUnmounted, computed} from 'vue'
import request from '../../utils/request'
import {fa, th, tr} from 'element-plus/es/locales.mjs'
import {ElNotification} from 'element-plus'
import {useLoading} from '../../utils/loading'
import {useStore} from "vuex";

const store = useStore()
const username = computed(() => store.state.auth.user)

const dateValue = ref<[Date, Date]>([
  new Date(),
  new Date(),
])


const columns = [{
  prop: 'workshop',
  label: '生产车间',
  width: '100'
}, {
  prop: 'printDate',
  label: '打印时间',
  width: '180'
}, {
  prop: 'printPerson',
  label: '打印人员',
  width: '100'
}, {
  prop: 'machine',
  label: '机台',
  width: '100'
}, {
  prop: 'designNo',
  label: '品号',
  width: '100'
}, {
  prop: 'cpTypeNo',
  label: '品名',
  width: '300'
}, {
  prop: 'ration',
  label: '定量',
  width: '70'
}, {
  prop: 'pilesNum',
  label: '层数',
  width: '70'
}, {
  prop: 'extent',
  label: '宽幅',
  width: '70'
}, {
  prop: 'diameter',
  label: '直径',
  width: '70'
}, {
  prop: 'weight',
  label: '标签重量',
  width: '90'
}, {
  prop: 'orderBillcode',
  label: '销售单号',
  width: '150'
}, {
  prop: 'label',
  label: '标签',
  width: '240'
}, {
  prop: 'labelStatus',
  label: '标签状态',
  width: '100'
}, {
  prop: 'dailyCapacity',
  label: '类型',
  width: '150'
}, {
  prop: 'version',
  label: 'app版本',
  width: '100'
}]

const statisticsStatusArr = ['已统计', '未统计']
const labeltatusArr = ['未入库', '已入库', '已销售', '已扫描', '已领料', '已报工']

const loading = ref(false)
const formData = ref({})

const today = new Date();

// 创建新对象并减去一天
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);

// 格式化为 YYYY-MM-DD
const year = yesterday.getFullYear();
const month = String(yesterday.getMonth() + 1).padStart(2, '0'); // 月份从0开始需+1
const day = String(yesterday.getDate()).padStart(2, '0');

formData.value.collectDate = `${year}-${month}-${day}`;


// 获取并格式化当前时间（YYYY-MM-DD HH:mm:ss）
const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const url = {
  listUrl: '/dailyCapacity/list',
  querySelectionUrl: '/dailyCapacity/querySelection',
  submitUrl: '/dailyCapacity/submit',
}

// 生命周期钩子：组件挂载时获取数据
onMounted(async () => {
  tableHeight.value = window.innerHeight - 300

  formData.value.labelDate = getCurrentTime();
  formData.value.labelDateEnd = getCurrentTime();
  handleList()
  httpQuerySelection()

})

// 打开帆软报表
const handleExport = () => {
  let url = "http://192.168.0.223:8080/webroot/decision/view/report?viewlet=DQ/LianGuiLabelStatistice.cpt";
  debugger
  Object.keys(formData.value).forEach(key => {
    url += "&" + key + "=" + encodeURIComponent(formData.value[key])
  })
  window.open(url)
}
const handleSubmit = () => {
  if (multipleSelection.value.length <= 0) {
    ElNotification.warning({
      title: '警告',
      message: '请勾选数据'
    })
    return
  }
  if (!formData.value.collectDate) {
    ElNotification.warning({
      title: '警告',
      message: '选择日期'
    })
    return
  }
  const validate = validateSelection()
  if (!validate) {
    ElNotification.warning({
      title: '警告',
      message: '请勾选同车间，同机台'
    })
    return
  }

  const loading = useLoading()
  console.log("username", username.value)
  request({
    url: url.submitUrl,
    method: 'post',
    params: {
      username: username.value,
      collectDate: formData.value.collectDate
    },
    data: multipleSelection.value
  }).then(res => {
    if (res.code == 200) {
      ElNotification.success({title: '成功提示', message: '提交成功'})
      handleList()
      return
    }
    ElNotification.error({title: '错误提示', message: res.message})
  }).catch(err => {
    ElNotification.error({title: '错误提示', message: err.message})
  }).finally(() => {
    loading.close()
  })
}

const validateSelection = () => {
  // 获取第一个项目作为参考基准
  const first = multipleSelection.value[0];

  // 检查所有项目是否与第一个项目具有相同的 workshop 和 machine
  return multipleSelection.value.every(item =>
      item.workshop === first.workshop &&
      item.machine === first.machine
  );
};

// 工作中心修改
const showMachineList = ref([])
const handleWorkshopChange = (val) => {
  showMachineList.value = machineList.value.filter(item =>
      item.includes(val)
  );
  console.log(showMachineList)
}

// 下拉框数据
const workshopList = ref([])
const machineList = ref([])


const httpQuerySelection = () => {
  request({
    url: url.querySelectionUrl,
    method: 'get'
  }).then(response => {
    console.log('response', response)

    workshopList.value = response.data.workshopList
    showMachineList.value = response.data.machineList
    machineList.value = response.data.machineList
  }).catch(err => {
    console.log('err', err)
  }).finally(() => {
  })
  // const response = request.get(url.querySelectionUrl)
  // console.log('response.data.workshopList', response)
}

// 表格数据
const tableData = ref()
const handleList = async () => {
  try {

    loading.value = true
    request({
      url: url.listUrl,
      method: 'get',
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        ...formData.value
      }
    }).then(response => {
      tableData.value = response.data
      total.value = response.total
    }).finally(() => {
      loading.value = false
    })
  } catch (error) {
    console.log('error', error)
  }
}

// 分页

const total = ref()
const currentPage = ref(1)
const pageSize = ref(50)
const handleSizeChange = (val: number) => {
  handleList()
}
const handleCurrentChange = (val: number) => {
  handleList()
}


// 多选
const collect = ref({})
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  collect.value.num = val.length
  collect.value.weight = val.reduce((sum, item) => {
    return sum + (Number(item.weight) || 0); // 处理非数字值
  }, 0)
}

const tableRef = ref();
const handleRowClick = (row) => {
  tableRef.value.toggleRowSelection(row); // 切换当前行选中状态
};


const tableHeight = ref(0);

</script>
<style>
/* main-container全局样式 */
.app-container {
  padding: 0px;
  height: calc(100vh - 94px);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.center {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
</style>
